package com.itheima.stock.service.Impl;

import com.google.common.collect.Lists;
import com.itheima.stock.common.StockInfoConfig;
import com.itheima.stock.common.domain.InnerMarketDomain;
import com.itheima.stock.mapper.StockBlockRtInfoMapper;
import com.itheima.stock.mapper.StockBusinessMapper;
import com.itheima.stock.mapper.StockMarketIndexInfoMapper;
import com.itheima.stock.pojo.StockBlockRtInfo;
import com.itheima.stock.pojo.StockMarketIndexInfo;
import com.itheima.stock.pojo.StockRtInfo;
import com.itheima.stock.service.StockTimerService;
import com.itheima.stock.utils.IdWorker;

import com.itheima.stock.utils.ParserStockInfoUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.apache.poi.hpsf.Decimal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.naming.ldap.PagedResultsResponseControl;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
@Service("stockTimerService")
public class StockTimerServiceImpl implements StockTimerService {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private StockInfoConfig stockInfoConfig;
    @Autowired
    private ParserStockInfoUtil parserStockInfoUtil;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private StockMarketIndexInfoMapper stockMarketIndexInfoMapper;
    @Autowired
    private StockBusinessMapper stockBusinessMapper;
    @Autowired
    private StockBlockRtInfoMapper stockBlockRtInfoMapper;
    @Override
    public void getInnerMarketInfo() {
        stockInfoConfig.getInner();
        String xx = stockInfoConfig.getMarketUrl() + String.join(",",
                stockInfoConfig.getInner());
        //发送请求获取大盘数据
        String forObject = restTemplate.getForObject(xx, String.class);
        //解析数据，封装结果集
        String rey="var hq_str_(.+)=\"(.+)\";";
        Pattern compile = Pattern.compile(rey);
        Matcher matcher = compile.matcher(forObject);
        ArrayList<StockMarketIndexInfo> infos = new ArrayList<>();
        while (matcher.find()){
            String marketCode=matcher.group(1);
            //其他信息
            String[] others=matcher.group(2).split(",");
            //大盘名称
            String marketName = others[0];
            //大盘点数
            BigDecimal curPoint = new BigDecimal(others[1]);
            //当前价格
            BigDecimal curPrice = new BigDecimal(others[2]);
            //振幅
            BigDecimal updownRate = new BigDecimal(others[3]);
            //成交量
            Long tradeCount = Long.valueOf(others[4]);
            //成交金额
            Long tradeVolume = Long.valueOf(others[5]);
            StockMarketIndexInfo smi = StockMarketIndexInfo.builder().id(idWorker.nextId())
                    .markId(marketCode)
                    .curTime(new Date())
                    .markName(marketName)
                    .curPoint(curPoint)
                    .currentPrice(curPrice)
                    .updownRate(updownRate)
                    .tradeAccount(tradeCount)
                    .tradeVolume(tradeVolume)
                    .build();
            infos.add(smi);
        }
        log.info("共：{}条数据,内容为：{}",infos.size(),infos.toString());
        //TODO 后续完成国内大盘批量插入的功能
        stockMarketIndexInfoMapper.insertBatch(infos);
    }

    @Override
    public void getStockRtIndex() {
        List<String> strings= stockBusinessMapper.getStockIds();
        strings = strings.stream().map(id -> {
            return id.startsWith("6") ? "sh" + id : "sz" + id;
        }).collect(Collectors.toList());
        Lists.partition(strings,20).forEach(list -> {
            String stock=stockInfoConfig.getMarketUrl()+String.join(",",list);
            String reslt = restTemplate.getForObject(stock, String.class);
            List<StockRtInfo> infos = parserStockInfoUtil.parser4StockOrMarketInfo(reslt,3);
            log.info("数据量：{}",infos.size());
            stockBusinessMapper.insertBatch(infos);
        });

    }

    @Override
    public void getStockSectorRtIndex() {
        String result = restTemplate.getForObject(stockInfoConfig.getBlockUrl(), String.class);
        List<StockBlockRtInfo> infos = parserStockInfoUtil.parse4StockBlock(result);
        log.info("板块数量：{}",infos.size());
        Lists.partition(infos,20).forEach(list->{
            stockBlockRtInfoMapper.insertBatch(list);
        });

    }
}